package com.nami.conver.domain.pchat.service.impl;


import com.nami.conver.domain.handler.ConverSyncHandler;
import com.nami.conver.domain.pchat.model.ConverModel;
import com.nami.conver.domain.pchat.model.UpdConverModel;
import com.nami.conver.domain.pchat.service.PrivateConverDomainService;
import com.nami.conver.domain.repository.CacheConverRepository;
import com.nami.conver.domain.repository.ConverRepository;
import com.nami.conver.types.util.ConverUtil;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

@Slf4j
@Component
@RequiredArgsConstructor
public class PrivateConverDomainServiceImpl implements PrivateConverDomainService {

    private final ConverRepository converRepository;
    private final CacheConverRepository cacheConverRepository;
    private final ConverSyncHandler syncHandler;


    @Override
    public void refreshConver(UpdConverModel converDomain) {
        String senderId = converDomain.getSenderId();
        String receiverId = converDomain.getReceiverId();
        if (converDomain.isRevert()) {
            senderId = converDomain.getReceiverId();
            receiverId = converDomain.getSenderId();
        }

        final ConverModel converMe = cacheConverRepository.get(ConverUtil.genPrivateConverKey(converDomain.getAppKey(),
            senderId, receiverId));
        if (null == converMe) {
            ConverModel conversation = this.getConverFromCacheOrDB(converDomain.getAppKey(), senderId, receiverId);
            if (null == conversation) {
                // Todo
                // 创建会话
                // 保存会话
                conversation = new ConverModel();
                conversation.setIfMute(false);
                conversation.setIfTop(false);
            }
            ConverModel needAdd = new ConverModel();

            needAdd.setAppKey(converDomain.getAppKey());

            needAdd.setConverType(1);
            needAdd.setUserId(senderId);
            needAdd.setTargetId(receiverId);

            needAdd.setIfMute(conversation.getIfMute());
            needAdd.setIfTop(conversation.getIfTop());

            needAdd.setTopUpdatedTime(conversation.getTopUpdatedTime());

            needAdd.setLatestMsgId(converDomain.getMessageId());
            needAdd.setLatestUnreadMsgIndex(converDomain.getSeq());
            needAdd.setSyncTime(converDomain.getTime());
            needAdd.setSortTime(converDomain.getTime());
            if (conversation.getLatestUnreadMsgIndex() != null && conversation.getLatestUnreadMsgIndex() > converDomain.getSeq()) {
                needAdd.setLatestMsgId(conversation.getLatestMsgId());
                needAdd.setLatestUnreadMsgIndex(conversation.getLatestUnreadMsgIndex());
                needAdd.setSyncTime(conversation.getSyncTime());
                needAdd.setSortTime(conversation.getSortTime());
                log.warn("[c2c] 更新会话出现问题，数据库数据为最新数据。");
            }

            needAdd.setLatestReadMsgId(conversation.getLatestReadMsgId());
            needAdd.setLatestReadMsgIndex(conversation.getLatestReadMsgIndex());
            cacheConverRepository.insertOrUpd(ConverUtil.genPrivateConverKey(converDomain.getAppKey(), senderId, receiverId), needAdd);
            syncHandler.handler(ConverUtil.genPrivateConverKey(converDomain.getAppKey(), senderId, receiverId));

            // 不用立即刷新会话，加入堆积队列即可，统一刷新
//            syncHandler.writeNow(ConverUtil.genPrivateConverKey(appKey, senderId, receiverId));
            return;
        }
        ConverModel updConver = converMe.clone();
        updConver.setLatestMsgId(converDomain.getMessageId());
        updConver.setLatestUnreadMsgIndex(converDomain.getSeq());
        updConver.setSyncTime(converDomain.getTime());
        updConver.setSortTime(converDomain.getTime());
        cacheConverRepository.insertOrUpd(ConverUtil.genPrivateConverKey(converDomain.getAppKey(), senderId, receiverId), updConver);
//        syncHandler.writeNow(ConverUtil.genPrivateConverKey(appKey, senderId, receiverId));
        syncHandler.handler(ConverUtil.genPrivateConverKey(converDomain.getAppKey(), senderId, receiverId));
    }

    private ConverModel getConverFromCacheOrDB(String appKey, String senderId, String receiverId) {
        ConverModel converDomain = cacheConverRepository.get(appKey, senderId, receiverId);
        if (converDomain == null) {
            ConverModel conversation = converRepository.getConversation(appKey, senderId, receiverId);
            if (conversation == null) {
                return null;
            }
            cacheConverRepository.writeConver(conversation);
            return conversation;
        }

        return converDomain;
    }

}
